package net.bat.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bat.db.BaseDAOImpl;
import net.bat.util.Cfg;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import dao.hb.UOrg;


public class getUorgTreeSerlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	static BaseDAOImpl baseDao = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
	private Gson gson=new GsonBuilder().setPrettyPrinting().create();
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.选择上级为空的数据 作为根节点
		//2.选择上级为1中查询出的数据 为二级  拼接map
		//3.一次类推
	//写一个递归方法,传入一个父ID或者字符串,返回其所有儿子的map			
		doPost(request,response);
	}
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List HList=getHightestList();
		List treeList=bulidTreeList(HList);
		String jstr = gson.toJson(treeList);	
		System.out.println(jstr);
		System.out.println("xxxxxxxxxxxxxxxx");		
	}
	public static List bulidIdList(List<UOrg> list){	
		List idList=new ArrayList();
		for(int i=0;i<list.size();i++){
			idList.add(list.get(i).getId());
		}					
		return idList;
	}
	public static List bulidTreeList(List list){
		List FList=new ArrayList();
		for(int i=0;i<list.size();i++){
			String id=list.get(i).toString();
			if(hasSon(id)){
				List Slist=getSonList(id);
				List sNameList=bulidTreeList(Slist);
				FList.add(sNameList);
			}else{
				FList.add(id);
			}			
		}
		return FList;
	}
	//判断是否有子机构
	public static boolean hasSon(String id){
		Session session = baseDao.getSessionFactory().getCurrentSession();
		boolean f=false;
		String sql="select * from  U_Org where pid='"+id+"'";	
		SQLQuery query = session.createSQLQuery(sql);
		List list = (List)query.list(); 
		if(list.size()>0){
			f=true;
		}
		return f;
	}
	//返回子机构结果集
	public static List getSonList(String fatherId){
		Session session = baseDao.getSessionFactory().getCurrentSession();
		String sql="select * from  U_Org where pid='"+fatherId+"'";	
		SQLQuery query = session.createSQLQuery(sql);
		List list = (List)query.list(); 
		return list;
	}
	//返回最高机构--无上级的根结点
		public static List getHightestList(){
			Session session = baseDao.getSessionFactory().getCurrentSession();
			String sql="select * from  U_Org where pid is null";	
			SQLQuery query = session.createSQLQuery(sql);
			List list = (List)query.list(); 
			return list;
		}
}
